const router = require('koa-router')();
const scripts = require('./scripts/account');

router.prefix('/api/rbac', '基于角色的权限管理相关接口');

router.post('/users/search', async (ctx) => {
  let json = ctx.request.body || {};

  let so = {
    pageIndex: json.pageIndex || 1,
    pageSize: json.pageSize || 20,
    filters: []
  };

  if (json.account) {
    so.filters.push({ field: 'Accouant', op: 'like', value: json.account });
  }

  if (json.userName) {
    so.filters.push({ field: 'UserName', op: 'like', value: json.userName });
  }

  if (json.roleId) {
    so.roleId = json.roleId;
    so.$totalSql$ = scripts.userSearchExceptRoleCount;
  }

  ctx.body = await ctx.sqlite.queryForList(json.roleId ? scripts.userSearchExceptRole : scripts.userSearch, so);
}, {
  desc: '查询用户信息',
  body: {
    pageIndex: { type: 'integer', desc: '页序号' },
    pageSize: { type: 'integer', desc: '每页显示数据大小' },
    account: { type: 'string', desc: '账号' },
    userName: { type: 'string', desc: '用户名' },
    roleId: { type: 'integer', desc: '当前角色编号' }
  }
});

router.post('/roles/search', async (ctx) => {
  let json = ctx.request.body || {};

  let so = {
    pageIndex: json.pageIndex || 1,
    pageSize: json.pageSize || 20,
    filters: []
  };

  if (json.name) {
    so.filters.push({ field: 'Name', op: 'like', value: json.name });
  }

  ctx.body = await ctx.sqlite.queryForList(scripts.roleSearch, so);
}, {
  desc: '查询用户信息',
  body: {
    pageIndex: { type: 'integer', desc: '页序号' },
    pageSize: { type: 'integer', desc: '每页显示数据大小' },
    name: { type: 'string', desc: '名称' }
  }
});

router.post('/role/create', async (ctx) => {
  let data = ctx.request.body || {};
  let rs = ctx.getResponse();

  if (!data.name) {
    rs.success = false;
    rs.message = '缺少角色名！';
  }

  if (!rs.success) {
    ctx.body = rs;

    return;
  }

  let role = await ctx.sqlite.queryForObject(scripts.getRole, { name: data.name });

  if (role.data) {
    rs.success = false;
    rs.message = '该角色已存在！';

    ctx.body = rs;

    return;
  }

  let createRs = await ctx.sqlite.execute(scripts.createRole, { name: data.name, createdOn: rs.at });

  ctx.body = createRs;
}, { desc: '添加角色', body: { name: { type: 'string', desc: '角色名称' } } });

router.put('/role/update', async (ctx) => {
  let data = ctx.request.body || {};
  let rs = ctx.getResponse();

  if (!data.id) {
    rs.success = false;
    rs.message = '缺少角色编号！';
  } else if (!data.name) {
    rs.success = false;
    rs.message = '缺少新角色名！';
  }

  if (!rs.success) {
    ctx.body = rs;

    return;
  }

  let role = await ctx.sqlite.queryForObject(scripts.getRoleById, { id: data.id });

  if (!role.data) {
    rs.success = false;
    rs.message = '该角色不存在！';

    ctx.body = rs;

    return;
  }

  let roleCheck = await ctx.sqlite.queryForObject(scripts.checkRoleName, data);

  if (roleCheck.data) {
    rs.success = false;
    rs.message = '该角色名已存在！';

    ctx.body = rs;

    return;
  }

  rs = await ctx.sqlite.execute(scripts.updateRole, data);

  ctx.body = rs;
}, {
  desc: '更新角色信息', body: {
    id: { type: 'integer', desc: '角色编号' },
    name: { type: 'string', desc: '新角色名称' }
  }
});

router.delete('/role/:id', async (ctx) => {
  let roleId = ctx.params.id;

  let roleRes = await ctx.sqlite.queryForObject(scripts.getRoleById, { id: roleId });

  if (roleRes.data && roleRes.data.Name == '超级管理员') {
    ctx.body = ctx.getResponse('超级管理员角色不能直接删除！');

    return;
  }

  ctx.body = await ctx.sqlite.execute(scripts.removeRole, { roleId });
}, { desc: '删除角色', id: '角色编号' });

router.post('/role/:id/users', async (ctx) => {
  let json = ctx.request.body || {};

  let so = {
    pageIndex: json.pageIndex || 1,
    pageSize: json.pageSize || 20,
    filters: [{ field: 'b.RoleId', op: '=', value: ctx.params.id }]
  };

  ctx.body = await ctx.sqlite.queryForList(scripts.searchRoleUsers, so, builder => {
    builder.and(`(a.Account like '%' || @keywords || '%' or a.UserName like '%' || @keywords || '%')`);
  });
}, {
  desc: '查询角色用户信息',
  body: {
    pageIndex: { type: 'integer', desc: '页序号' },
    pageSize: { type: 'integer', desc: '每页显示数据大小' },
    keywords: { type: 'string', desc: '关键字' }
  }
});

router.post('/role/:id/addUsers', async (ctx) => {
  let roleId = ctx.params.id;
  let datas = ctx.request.body || [];

  let items = datas.map(d => {
    return { roleId: roleId, userId: d }
  });

  ctx.body = await ctx.sqlite.execute(scripts.addRoleUser, items);
}, { desc: '添加角色用户', id: '角色编号' });

router.delete('/role/:roleId/:userId', async (ctx) => {
  let roleId = ctx.params.roleId;
  let userId = ctx.params.userId;

  ctx.body = await ctx.sqlite.execute(scripts.removeRoleUser, { roleId, userId });
}, { desc: '删除角色用户', roleId: '角色编号', userId: '用户编号' });

module.exports = router;